﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MenuLib;

namespace MenuBuilder
{
    class Program
    {
        static void Main(string[] args)
        {
            StartBuilder();
        }

        static void StartBuilder()
        {
            Menu selectModeMenu = new Menu();
            selectModeMenu.Text = "SELECT MENU BUILDER MODE";

            MenuItem item = new MenuHotKeyedItem(
                "Create", "_Create new menu from scratch", 'c');
            item.Select += new EventHandler(item_Create);
            selectModeMenu.Items.Add(item);

            item = new MenuHotKeyedItem(
                "Modify", "_Modify already created before menu", 'm');
            item.Select += new EventHandler(item_Modify);
            selectModeMenu.Items.Add(item);

            selectModeMenu.Run();
        }

        static void item_Create(object sender, EventArgs e)
        {
            while (true)
            {
                Console.Write("Type the title for the new menu to build: ");

                string title = Console.ReadLine();

                if (string.IsNullOrEmpty(title))
                {
                    Console.WriteLine("Type non empty title");
                    continue;
                }

                Menu newMenu = new Menu();
                newMenu.Text = title;
                MenuBuilder builder = new MenuBuilder(newMenu);
                MenuBuilderMenu builderMenu = new MenuBuilderMenu(builder);

                builderMenu.Run();

                break;
            }
        }

        static void item_Modify(object sender, EventArgs e)
        {
            string[] menuFiles = Directory.GetFiles(".", "*.bin", SearchOption.AllDirectories);

            if (menuFiles.Length > 0)
            {
                Console.WriteLine("Available menu files");
                Array.ForEach(menuFiles, file => Console.WriteLine("\t{0}", file));
            }

            while (true)
            {
                Console.Write("Type path to menu file: ");
                string path = Console.ReadLine();

                if (string.IsNullOrEmpty(path))
                {
                    break;
                }

                try 
	            {
                    Menu menuToModify = Menu.Load(path);
                    MenuBuilder builder = new MenuBuilder(menuToModify);
                    MenuBuilderMenu builderMenu = new MenuBuilderMenu(builder);

                    builderMenu.Run();

                    break;
	            }
	            catch (Exception ex)
	            {
                    Console.WriteLine("Failed to load the menu specified:\n{0}", ex.Message);
                    continue;
	            }
            }
        }
    }
}
